package com.whp02.annotation.bd;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractRefreshableConfigApplicationContext;
import org.springframework.lang.Nullable;

import java.io.IOException;

/**
 * @author wanghp
 * @version 1.0
 * @description: TODO
 * @date 2020/12/1 11:57
 */
public class ClassPathPropertyFileApplicationContext extends AbstractRefreshableConfigApplicationContext {
	String[] configLocations;

	public ClassPathPropertyFileApplicationContext(String[] s, @Nullable ApplicationContext parent) {
		//super(parent);
		this.configLocations = s;
		setConfigLocations(configLocations);
		if (true) {
			refresh();
		}
	}

	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// 构造一个propertiesBeanDefinitionReader，就是前面我们的主角
		PropertiesBeanDefinitionReader beanDefinitionReader = new PropertiesBeanDefinitionReader(beanFactory);

		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		loadBeanDefinitions(beanDefinitionReader);
	}

	//使用reader，加载bean definition
	protected void loadBeanDefinitions(PropertiesBeanDefinitionReader reader) throws BeansException, IOException {
		String[] configResources = getConfigLocations();
		if (configResources != null) {
			//看这，兄弟
			reader.loadBeanDefinitions(configResources);
		}
	}

	public ClassPathPropertyFileApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}
}
